package com.zk.shop.servlet.Cart;

import com.zk.shop.entity.CartItem;
import com.zk.shop.entity.User;
import com.zk.shop.service.CartService;
import com.zk.shop.service.Impl.CartServiceImpl;
import com.zk.shop.util.CartCookieUtil;
import com.zk.shop.util.JSONServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/ShowCartServlet")
public class ShowCartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CartService cartService = new CartServiceImpl();
        User user = (User) request.getSession().getAttribute("user");
        List<CartItem> cartItemList;
        if(user == null){   //如果用户未登录从 cookie 中取
            cartItemList = CartCookieUtil.getCart(request);
        }else{  //如果已登录从数据库中取
            cartItemList = cartService.showCart(user);
        }
        JSONServlet.getJson(request,response,cartItemList);
    }
}
